import { Application } from 'egg';
import { DataTypes, Model } from 'sequelize';

export interface CommentAttributes {
  id?: number;
  restaurant_id: number;
  user_id: number;
  content: string;
  grade: number;
  pictures: string;
  created_at?: Date;
  updated_at?: Date;
}

export interface CommentInstance extends Model<CommentAttributes>, CommentAttributes {}

export default (app: Application) => {
  const { INTEGER, TEXT, DECIMAL, DATE } = DataTypes;

  const Comment = app.model.define<CommentInstance>('Comment', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    restaurant_id: {
      type: INTEGER,
      allowNull: false,
      comment: '美食店ID',
    },
    user_id: {
      type: INTEGER,
      allowNull: false,
      comment: '用户ID',
    },
    content: {
      type: TEXT,
      allowNull: false,
      comment: '评论内容',
    },
    grade: {
      type: DECIMAL(3, 2),
      allowNull: false,
      comment: '评分',
    },
    pictures: {
      type: TEXT,
      allowNull: true,
      comment: '图片链接，JSON格式',
    },
    created_at: {
      type: DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updated_at: {
      type: DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  }, {
    tableName: 'comments',
    comment: '评论表',
  });

  // 关联关系
  // 定义关联关系
  (Comment as any).associate = () => {
    app.model.Comment.belongsTo(app.model.Restaurant, { foreignKey: 'restaurant_id', as: 'restaurant' });
    app.model.Comment.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
  };

  return Comment;
};